var logger = require('./logger');
var wxToken = require('./wx-token');

const POLL_INTERVAL = 1000 * 5; // 轮询间隔 TODO
const MAX_FAIL_CNT = 10; // 最多失败调用次数 TODO

class Client {

    /**
     * 构造函数
     */
    constructor() {
        this.failCnt = 0; // 失败计数
        this.stopFlag = false; // 轮询停止标志
    }

    _delay(delayTime = 0) {

        this.ref = setTimeout(async() => {
            if (this.stopFlag) {
                logger.debug(`[Client] 停止轮询微信token`);
                return;
            }

            logger.debug(`[Client] 延迟${POLL_INTERVAL}获取微信token`);
            let token = await wxToken.get(true);
            logger.debug(`[Client] 获取微信token调用次数共计: ${wxToken.invokeCount}`);
            if (token == null) {
                if (++this.failCnt <= MAX_FAIL_CNT) {
                    this._delay();
                } else {
                    logger.error(`[Client] 连续失败获取微信token达到最大次数: ${MAX_FAIL_CNT},停止重试！`);
                    this.failCnt = 0;
                }
            } else {
                this._delay(delayTime);
            }
        }, delayTime);
    }

    start() {
        logger.debug(`[Client] 启动轮询`);
        this.stopFlag = false;
        wxToken.get(true); // 启动首次调用
        this._delay(POLL_INTERVAL);
    }

    restart() {
        logger.debug(`[Client] 重启轮询`);
        this.stop();
        this.start();
    }

    stop() {
        logger.debug(`[Client] 停止轮询`);
        this.stopFlag = true;
        this.ref && clearTimeout(this.ref);
    }

    async refresh(oldToken) {
        logger.debug(`[Client] 刷新token`);
        let token = wxToken.get(false, oldToken);
        return token;
    }
}

module.exports = new Client();
